package com.example.demo.service.impl;

import com.example.demo.exception.bizException.BizException;
import com.example.demo.service.FileService;
import com.example.demo.util.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author: chenyu
 * @date: 2020/8/5 16:19
 */
@Service
@Slf4j
public class FileServiceImpl implements FileService {

    @Value("${web.upload-path}")
    private String path;

    @Value("${web.url}")
    private String url;

    @Override
    public String insert(MultipartFile file) {
        if(file==null){
            throw  new BizException("文件为空");
        }
        String filePath=path+"demand/";
        String fileName=file.getOriginalFilename();
        String newFileName = FileUtils.addFileNewNameByTime(fileName);
        try {
            FileUtils.upload(file.getBytes(),filePath,newFileName);
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return newFileName;
    }

    @Override
    public boolean delete(String fileName) {
        String photo=fileName.substring(fileName.lastIndexOf("/")+1);
        String filePath=path+"demand/"+photo;
        return FileUtils.deleteFile(filePath);
    }

    @Override
    public String insertUserPhoto(MultipartFile file) {
        String fileName=file.getOriginalFilename();
        log.info("开始上传头像{}",fileName);
        if(file==null){
            throw  new BizException("文件为空");
        }
        //判断是否为图片格式
        if(!FileUtils.judgeFileType(fileName.substring(fileName.lastIndexOf(".")+1))){
            log.error("文件不是图片格式，不能作为头像");
            throw new BizException("文件格式错误");
        }
        String filePath=path+"user/";
        String fileNewName= FileUtils.getFileNewName(file.getOriginalFilename());
        try {
            FileUtils.upload(file.getBytes(),filePath,fileNewName);
        } catch (Exception e) {
            log.error("文件上传失败，未知错误");
            throw new BizException("文件上传未知错误");
        }
        log.info("上传头像成功");
        return fileNewName;
    }
}
